package mts.testframework.testitems;
import java.util.Calendar;

import mts.ElevatorControllerInternalConnection;
import mts.NewEventTimestampListener;
import mts.constants.EventType;
import mts.groupdispatcher.FloorRequest;
import mts.messages.EventTimeStampMessage;


public class FloorRequestTestItem extends TestItem implements NewEventTimestampListener {

	TestItem[] onCompleted;
	private FloorRequest floorRequest;
	
	boolean alreadyCompleted = false;
	
	public FloorRequestTestItem(long delay, FloorRequest floorRequest, TestItem... onCompleted) {
		super(delay, onCompleted);
		this.floorRequest = floorRequest;
		this.onCompleted = onCompleted;
	}
	
	@Override
	public void start() {
		startTime = Calendar.getInstance().getTime();
		byte car = testItemScheduler.getGroupDispatcher().addFloorRequest(this.floorRequest);
		setCar(car);
		ElevatorControllerInternalConnection elevatorControllerInternalConnection = testItemScheduler.getElevatorControllerInternalConnectionServer().getElevatorControllerInternalConnection(car); 
		
		elevatorControllerInternalConnection.addOonNewEventTimestampListener(this);
	}
	
	@Override
	public void addEventTimeStamp(EventTimeStampMessage eventTimeStampMessage) {
		if (eventTimeStampMessage.getCurrentFloor() == floorRequest.getFloor() && eventTimeStampMessage.getEvent() == EventType.ARRIVAL) {
			complete();
		}		
	}

	@Override
	public void complete() {
		synchronized(this) {
			if (alreadyCompleted) {
				return;
			}
			alreadyCompleted = true;
		}
		endTime = Calendar.getInstance().getTime();
		testItemScheduler.logOutput(String.format("%d WAIT_TIME %d\n", id, getDeltaTime()  ));
		
		super.complete();
	}
}
